package com.cheneyjoo.view;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cheneyjoo.base.Login;
import com.cheneyjoo.model.RequestMessage;
import com.cheneyjoo.util.CheneyScanner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

public class UserLogin extends Login {
    public UserLogin(Socket socket,BufferedReader in,PrintStream out) throws IOException {
        super.setSocket(socket);
        super.setIn(in);
        super.setOut(out);
        super.setMenu(new UserMenu(socket,out,in));
    }
    @Override
    public void login() throws IOException {
        System.out.println("请输入账户：");
        String name = CheneyScanner.reader.readLine();
        System.out.println("请输入密码：");
        String pwd = CheneyScanner.reader.readLine();
        Map<String, Object> requestContent = new LinkedHashMap<>();
        requestContent.put("type", 2);
        requestContent.put("account", name);
        requestContent.put("pwd", pwd);
        RequestMessage rm = new RequestMessage("user", "login", requestContent);
        super.getOut().println(JSON.toJSONString(rm));
        String response =super.getIn().readLine();
        JSONObject result = JSON.parseObject(response);
        if (Optional.ofNullable(result.get("code")).isPresent()) {
            if ("200".equals(result.get("code").toString())) {
                System.out.println("登录成功！！！");
                Map<String,String> userMap=new HashMap<>();
                JSONObject jsonObject = JSONObject.parseObject(result.get("content").toString());
                userMap.put("id",jsonObject.getString("id"));
                userMap.put("account",jsonObject.getString("account"));
                userMap.put("name",jsonObject.getString("name"));
                super.getMenu().setUserMap(userMap);
                super.getMenu().menu();
            } else {
                System.out.println(result.get("message").toString());
                super.getOut().println("bye");
                String readLine = super.getIn().readLine();
                if ("*server close*".equals(readLine)) {
                    super.getIn().close();
                    super.getOut().close();
                }
            }
        }
    }
}
